package cn.com.open.ms.ecgpaasdatarest.service;

import cn.com.open.ms.ecgpaasdatarest.dynamicconfig.SwitchDataSource;
import cn.com.open.ms.ecgpaasdatarest.dynamicsql.DynamicSqlUtils;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description TODO
 * @Author 奶茶
 * Created by on 2018/11/30 15:25.
 */
@Service
public class BusinessService {

    private static final Logger logger = LoggerFactory.getLogger(BusinessService.class);

    @Autowired
    private SwitchDataSource switchDataSource;


    /**
     * 数据查询
     * @param appKey
     * @param businessName
     * @param tableName
     * @return
     * @throws SQLException
     */
    public List<Map<String,Object>> searchData(String appKey, String businessName, String tableName) throws SQLException {
        List<Map<String,Object>> mapList = new ArrayList<>();
        DruidDataSource druidDataSource = switchDataSource.dynamicSwitchDataBase(appKey, businessName);
        String sql = DynamicSqlUtils.getSQL(tableName);
        try(DruidPooledConnection connection = druidDataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(sql);ResultSet resultSet = statement.executeQuery()) {
            while (resultSet.next()){
                HashMap<String, Object> map = new HashMap<>();
                ResultSetMetaData data = resultSet.getMetaData();
                int columnCount = data.getColumnCount();
                for (int i=1; i<=columnCount; i++) {
                    map.put(data.getColumnLabel(i), resultSet.getObject(i));
                }
                mapList.add(map);
            }
        }
        return mapList;
    }
}
